package com.yedean.mall.handler;

import com.yedean.mall.pojo.User;
import com.yedean.mall.service.UserService;
import org.springframework.http.MediaType;
import org.springframework.web.reactive.function.server.ServerRequest;
import org.springframework.web.reactive.function.server.ServerResponse;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

public class UserHandler {
    
    private final UserService userService;


    public UserHandler(UserService userService) {
        this.userService = userService;
    }
    
    
    //根据id查询用户
    public Mono<ServerResponse> getUserById(ServerRequest request){
        //获取id值
        int userId= Integer.parseInt(request.pathVariable("id"));
        //空值处理
        Mono<ServerResponse> notFound=ServerResponse.notFound().build();
        //调用service方法得到数据
        Mono<User> userMono = userService.getUserById(userId);
        
       return userMono.flatMap(person-> ServerResponse.ok()
               .contentType(MediaType.APPLICATION_JSON)
               .bodyValue(person))
               .switchIfEmpty(notFound);
    }
    
    
    //查询所有用户
    public Mono<ServerResponse> getAllUsers(ServerRequest serverRequest){
        //调用service方法得到结果
        Flux<User> allUser = userService.getAllUser();
        return ServerResponse.ok()
                .contentType(MediaType.APPLICATION_JSON)
                .bodyValue(allUser);
    }
    
    //添加用户
    public Mono<ServerResponse> saveUser(ServerRequest serverRequest){
        //得到user对象
        Mono<User> mono = serverRequest.bodyToMono(User.class);
        return ServerResponse.ok().build(this.userService.saveUser(mono));
    }
}
